/**
 * 创建右键菜单
 * chrome.contextMenus.create(obj);
 * obj.type = [
 *     "normal",       // 普通菜单
 *     "radio",        // 单选菜单
 *     "checkbox",     // 复选菜单
 *     "separator",    // 分割线
 * ]

 * obj.title       // 菜单名称
 * obj.id          // 菜单id
 * obj.checked     // 是否选择
 * obj.parentId    // 父菜单id，设置改值可以设置多级菜单
*/

/**
 * 添加右键菜单
 */
chrome.contextMenus.create({
    type: "normal",
    title: "自定义页面布局",
    id: "select",
    contexts: ["all"]
});

chrome.contextMenus.create({
    type: "normal",
    title: "贴边隐藏",
    id: "border",
    parentId: "select",
    contexts: ["all"]
});

chrome.contextMenus.create({
    type: "normal",
    title: "屏蔽元素",
    id: "selectElement",
    parentId: "select",
    contexts: ["all"],
    checked: false,
    onclick: function(info, tab){
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            chrome.tabs.sendMessage(tabs[0].id, {
                type: "select"
            }, () => {});
        });
    }
});

var global = {};

var callback = {
    open: function(value)
    {
        chrome.contextMenus.update("selectElement", {
            checked: value
        });
    }
}

var getTabObj = function()
{
    return {
        select: false
    }
}

var onChageTab = function(info)
{
    var id = info.tabId + "-" + info.windowId;
    if(Lyx.isUndefined(global[id]))
    {
        global[id] = getTabObj();
    }
    chrome.contextMenus.update("selectElement", {
        checked: global[info.tabId + "-" + info.windowId].select
    });
    console.log("onChangeTab");
}

var onUpdated = function(info)
{
    var obj = {};
    obj.select = false;
    global[info.tabId + "-" + info.windowId] = obj;
    onChageTab(info);
    console.log("update");
}

var onCloseTab = function(info)
{
    delete global[info.tabId + "-" + info.windowId];
    console.log("close");
}

chrome.extension.onMessage.addListener(function(obj){
    Lyx.each(obj, function(key, value){
        callback[key](value);
        console.log(key, value);
    });
});

chrome.tabs.onActivated.addListener(onChageTab);

chrome.tabs.onRemoved.addListener(onCloseTab);

chrome.tabs.onUpdated.addListener(onUpdated);

// chrome.tabs.onCreated.addListener(onCreateTab);